package cn.liumouren.tool.security.autoconfigure;

import cn.liumouren.tool.security.autoconfigure.component.SecurityHolder;
import cn.liumouren.tool.security.core.DlFilter;
import cn.liumouren.tool.security.core.DlFilterRegistry;
import cn.liumouren.tool.security.core.DlInterceptor;
import cn.liumouren.tool.security.core.DlInterceptorRegistry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import java.util.List;

/**
 * @author Daniel Liu
 * @date 2021/3/13 13:12
 */
@Configuration
@ConditionalOnProperty(value = "dl.security.enable", havingValue = "false")
@EnableConfigurationProperties(SecurityProperties.class)
public class DisabledAutoConfiguration {

    @Bean
    public SecurityHolder securityHolder(DlFilterRegistry dlFilterRegistry, DlInterceptorRegistry dlInterceptorRegistry) {
        SecurityHolder disable = new SecurityHolder();

        // 关闭过滤器
        List<DlFilter> filters = dlFilterRegistry.getFilters();
        for (DlFilter filter : filters) {
            filter.excludePatterns("/**");
        }

        disable.setFilterRegistry(dlFilterRegistry);
        disable.setInterceptorRegistry(dlInterceptorRegistry);
        disable.setEnable(false);

        return disable;
    }

    /**
     * 如果关闭, 放行所有拦截器
     */
    @Bean
    public DlInterceptorRegistry dlInterceptorRegistry(List<DlInterceptor> interceptors) {
        return new DlInterceptorRegistry() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                for (DlInterceptor in : interceptors) {
                    in.excludePatterns("/**");
                    registry.addInterceptor(in)
                            .excludePathPatterns("/**");
                }
            }
        };
    }


}
